﻿using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using LocalNas.Core.Attributes;
using LocalNas.Core.Const;
using LocalNas.Core.Enum;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Security.Permissions;
using System.Security.Policy;
using System.Threading.Tasks;

namespace LocalNas.Web.Core
{
    public class JwtHandler : AppAuthorizeHandler
    {
        /// <summary>
        /// 重写 Handler 添加自动刷新收取逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task HandleAsync(AuthorizationHandlerContext context)
        {
            // 自动刷新 token
            if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext()))
            {
                await AuthorizeHandleAsync(context);
            }
            else context.Fail();    // 授权失败
        }

        public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false

            //当前函数上的特性
            var permission = httpContext.GetMetadata<JustAdminAttribute>();
            if (permission != null)
            {
                if (System.Enum.Parse<UserTypeEnum>(App.User.FindFirst(ClaimConst.UserType)?.Value) != UserTypeEnum.超级管理员)
                {
                    return Task.FromResult(false);
                }
            }


            return Task.FromResult(true);
        }
    }
}